﻿using EasySchedule.DataModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using Windows.Storage;
using Windows.Storage.Streams;

namespace EasySchedule.ServiceAgent
{
    class ServiceGateway<T>
    {
        private ServiceManager manager;
        private StorageFolder localFolders;
        
        public ServiceGateway()
        {
            this.localFolders = ApplicationData.Current.LocalFolder;            
        }

        public ServiceGateway(string access_token,string access_token_secret) : this()
        {
            manager = new ServiceManager(access_token, access_token_secret);
        }

        public ServiceGateway(ServiceManager manager) : this()
        {
            this.manager = manager;
        }

        public async Task<T> GetModelData(string fileName)
        {            
            StorageFile storeageFile = await this.localFolders.GetFileAsync(fileName);

            XmlSerializer serializer = new XmlSerializer(typeof(T));

            string xml = await Windows.Storage.FileIO.ReadTextAsync(storeageFile);

            T model = (T)serializer.Deserialize(new StringReader(xml));

            return model;
        }

        public async Task<T> GetModelData(string addressUser, string fileName) 
        {
            StorageFile storeageFile = await this.localFolders.CreateFileAsync(fileName, 
                CreationCollisionOption.ReplaceExisting);
            
            var authzHeader = manager.GenerateAuthzHeader(addressUser, "GET");
            var request = (HttpWebRequest)WebRequest.Create(addressUser);
            request.Headers["Authorization"] = authzHeader;
            
            WebResponse response = await request.GetResponseAsync();
            Stream responseStream = response.GetResponseStream();

            var responseReader = new System.IO.StreamReader(responseStream);
            
            string responseString = responseReader.ReadToEnd();

            if (string.IsNullOrEmpty(responseString)) throw new InvalidOperationException("No service response") ;

            await FileIO.WriteTextAsync(storeageFile, responseString);
            
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            StringReader reader = new StringReader(responseString);
            T model = (T)serializer.Deserialize(reader);

            await responseStream.FlushAsync();
            reader.Dispose();
            return model;
            
        }

        public async Task<bool> FileExists(string fileName)
        {
            try            
            {
                StorageFile storeageFile = await this.localFolders.GetFileAsync(fileName);
                return (storeageFile != null);
            }
            catch (FileNotFoundException ex)
            {
                return false;
            }
            
            
        }
    }
}
